package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

public class DelOperation implements IOperation{
    @Override
    public void work(BookList booklist) {
        System.out.println("删除图书！");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入需要删除的图书的名字：");
        String name = scanner.nextLine();
        System.out.println("请输入图书的作者:");
        String author = scanner.nextLine();
        int currentSize = booklist.getUsedSize();
        int index=-1;
        for (int i = 0; i < currentSize; i++) {
            Book tempBook = booklist.getBook(i);
            if(tempBook.getName().equals(name)&&tempBook.getAuthor().equals(author)){
               index=i;//找到要删除的元素的下标
                break;
            }
        }
        //如果数组中已没有该书则删除失败！
        if(index==-1) {
            System.out.println("该书不存在！删除失败！");
            return;
        }
        for (int j = index; j < currentSize-1; j++) {
            Book book = booklist.getBook(j+1);
            booklist.setBook(book,j);
        }
        booklist.setUsedSize(currentSize-1);
        //因为删除的是对象，所以要把对象销毁
        booklist.setBook(null,currentSize-1);
        System.out.println("删除成功！");
    }
}
